// reducer
import { createSlice, createAsyncThunk } from '@reduxjs/toolkit'
import { fetchLogin, LoginType } from './loginApi'

export const fetchAsyncAction = createAsyncThunk('login/fetchLogin', async (values: LoginType) => {
  const result = await fetchLogin(values)
  return result.data
})

const loginSlice = createSlice({
  name: 'login',
  initialState: { token: '', loading: false },
  reducers: {
    set_token(state, action) {
      console.log('action:', action)
      state.token = action.payload
    },
  },
  extraReducers(builder) {
    builder.addCase(fetchAsyncAction.pending, (state, action) => {
      state.loading = true
    })
    builder.addCase(fetchAsyncAction.fulfilled, (state, action) => {
      state.token = action.payload.token
      state.loading = false
    })
  },
})

export default loginSlice.reducer

export const { set_token } = loginSlice.actions
